// 统一的HTTP请求客户端
import { toast } from './toast-with-audio';
// 模拟服务器导入已移除，用户、角色、菜单的模拟已迁移到各自的store模块
import { getApiBaseUrl, getConfigSync, shouldUseMockServer } from '../config/app.config';

// 异步获取API基础URL
let apiBaseUrlPromise: Promise<string> | null = null;

// 模块加载时自动初始化API基础URL
const initializeApiBaseUrl = () => {
  if (!apiBaseUrlPromise) {
    apiBaseUrlPromise = getApiBaseUrl();
  }
};

// 立即执行初始化
initializeApiBaseUrl();



// 请求配置接口
export interface RequestConfig {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  headers?: Record<string, string>;
  body?: any;
  timeout?: number;
}

// 响应接口
export interface HttpResponse<T = any> {
  data: T;
  status: number;
  statusText: string;
  headers: Record<string, string>;
  success: boolean;
  message?: string;
}

// 获取认证token（从localStorage或context中获取）
const getAuthToken = (): string | null => {
  // 这里可以从localStorage、context或全局状态中获取token
  // 暂时返回一个模拟的token，实际项目中应该从认证系统获取
  return localStorage.getItem('auth_token') || 'mock-auth-token-123456';
};



// 统一的请求函数
export async function httpClient<T = any>(
  url: string,
  config: RequestConfig = {}
): Promise<HttpResponse<T>> {
  const {
    method = 'GET',
    headers = {},
    body,
    timeout = 10000
  } = config;

  // 真实API请求
  // 设置默认请求头
  const defaultHeaders: Record<string, string> = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };

  // 添加认证头
  const authToken = getAuthToken();
  if (authToken) {
    defaultHeaders['Authorization'] = `Bearer ${authToken}`;
  }

  // 合并请求头
  const finalHeaders = {
    ...defaultHeaders,
    ...headers
  };

  // 创建请求配置
  const requestConfig: RequestInit = {
    method,
    headers: finalHeaders,
    ...(body && { body: JSON.stringify(body) })
  };

  // 创建超时控制器
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout);
  requestConfig.signal = controller.signal;

  try {
    const response = await fetch(url, requestConfig);
    
    // 清除超时定时器
    clearTimeout(timeoutId);

    // 解析响应数据
    let responseData;
    const contentType = response.headers.get('content-type');
    
    if (contentType && contentType.includes('application/json')) {
      responseData = await response.json();
    } else {
      responseData = await response.text();
    }

    // 构建响应对象
    const httpResponse: HttpResponse<T> = {
      data: responseData,
      status: response.status,
      statusText: response.statusText,
      headers: Object.fromEntries(response.headers.entries()),
      success: response.ok,
      message: response.ok ? '请求成功' : response.statusText
    };

    // 处理非200状态码
    if (!response.ok) {
      // 可以根据状态码进行不同的错误处理
      switch (response.status) {
        case 401:
          toast('认证失败，请重新登录');
          // 可以在这里触发登出逻辑
          break;
        case 403:
          toast('权限不足');
          break;
        case 404:
          toast('请求的资源不存在');
          break;
        case 500:
          toast('服务器内部错误');
          break;
        default:
          toast(`请求失败: ${response.statusText}`);
      }
      
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    return httpResponse;

  } catch (error) {
    // 清除超时定时器
    clearTimeout(timeoutId);

    if (error instanceof Error) {
      if (error.name === 'AbortError') {
        toast('请求超时，请检查网络连接');
        throw new Error('请求超时');
      }
      
      toast('网络请求失败，请检查网络连接');
      throw new Error(`网络错误: ${error.message}`);
    }
    
    throw error;
  }
}

// 便捷的请求方法
export const http = {
  get: <T = any>(url: string, config?: Omit<RequestConfig, 'method' | 'body'>) => 
    httpClient<T>(url, { ...config, method: 'GET' }),
  
  post: <T = any>(url: string, data?: any, config?: Omit<RequestConfig, 'method' | 'body'>) => 
    httpClient<T>(url, { ...config, method: 'POST', body: data }),
  
  put: <T = any>(url: string, data?: any, config?: Omit<RequestConfig, 'method' | 'body'>) => 
    httpClient<T>(url, { ...config, method: 'PUT', body: data }),
  
  delete: <T = any>(url: string, config?: Omit<RequestConfig, 'method' | 'body'>) => 
    httpClient<T>(url, { ...config, method: 'DELETE' }),
  
  patch: <T = any>(url: string, data?: any, config?: Omit<RequestConfig, 'method' | 'body'>) => 
    httpClient<T>(url, { ...config, method: 'PATCH', body: data })
};

// 直接使用app.config.ts中导出的函数
export const getAPI_BASE_URL = getApiBaseUrl;

// 同步获取API基础URL（不包含运行时配置）
export const getAPI_BASE_URL_SYNC = () => getConfigSync().api.baseUrl;

